package com.me.learnspring.utils;

import cn.hutool.core.util.NumberUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.io.IOException;

public class MoneyDeserializer extends JsonDeserializer<Money> {
	@Override
	public Money deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
		String text = jsonParser.getText();
		if (NumberUtil.isNumber(text)) {
			return Money.of(CurrencyUnit.of("CNY"), NumberUtil.toBigDecimal(text));
		}
		throw new IOException(String.format("%s无法被反序列化为%s", text, Money.class));
	}
}
